package be.webchess.www.tiles;

import java.lang.reflect.Method;
import java.util.Collection;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.jasper.tagplugins.jstl.core.ForEach;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.ServletDispatcherResult;
import org.apache.tiles.Attribute;
import org.apache.tiles.AttributeContext;
import org.apache.tiles.TilesContainer;
import org.apache.tiles.access.TilesAccess;

import be.webchess.www.actions.BaseAction;
import be.webchess.www.actions.ajax.AjaxBaseAction;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;

/**
 * <!-- START SNIPPET: description -->
 * Renders a view using struts-tiles.
 * <!-- END SNIPPET: description -->
 *
 * <!-- START SNIPPET: webxml -->
 * In your web.xml file, you need to add a servlet entry for TilesServlet to load the tiles
 * definitions into the ServletContext.
 *
 * &lt;servlet&gt;
 *      &lt;servlet-name&gt;tiles&lt;/servlet-name&gt;
 *      &lt;servlet-class&gt;org.apache.tiles.servlets.TilesServlet&lt;/servlet-class&gt;
 *      &lt;init-param&gt;
 *          &lt;param-name&gt;definitions-config&lt;/param-name&gt;
 *          &lt;param-value&gt;/WEB-INF/tiles-config.xml&lt;/param-value&gt;
 *      &lt;/init-param&gt;
 *      &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
 * &lt;/servlet&gt;
 * <!-- END SNIPPET: webxml -->
 *
 * <!-- START SNIPPET: strutsxml -->
 * In struts.xml, use type="tiles" on your &lt;result&gt;.
 *
 * &lt;action name="editUser" class="userAction" method="edit"&gt;
 *      &lt;result name="success" type="tiles"&gt;userForm&lt;/result&gt;
 *      &lt;result name="input" type="tiles"&gt;userList&lt;/result&gt;
 * &lt;/action&gt;
 * <!-- END SNIPPET: strutsxml -->
 *
 *
 * <!-- START SNIPPET: packageconfig -->
 *
 * Making this result type the default for the current package.
 *
 * &lt;result-types&gt;
 *      &lt;result-type name="tiles"
 * class="org.apache.struts2.views.tiles.TilesResult" default="true" /&gt;
 * &lt;/result-types&gt;
 * <!-- END SNIPPET: packageconfig -->
 *
 */
public class TilesResult extends ServletDispatcherResult {

    private static final long serialVersionUID = -3806939435493086244L;

    public TilesResult() {
        super();
    }

    public TilesResult(String location) {
        super(location);
    }
    /**
     * Dispatches to the given location. Does its forward via a RequestDispatcher. If the
     * dispatch fails a 404 error will be sent back in the http response.
     *
     * @param location the location to dispatch to.
     * @param invocation    the execution state of the action
     * @throws Exception if an error occurs. If the dispatch fails the error will go back via the
     *                   HTTP request.
     */
    public void doExecute(String location, ActionInvocation invocation) throws Exception {
        setLocation(location);

        ServletContext servletContext = ServletActionContext.getServletContext();
        TilesContainer container = TilesAccess.getContainer(servletContext);

        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();

        AttributeContext attributeContext = container.startContext(request,
                response);
        
        try
        {
        	if ( invocation.getResultCode().compareTo(ActionSupport.SUCCESS) == 0 )
        	{
	        	if ( invocation.getAction() instanceof BaseAction )
	        	{
	        		BaseAction		a = (BaseAction)invocation.getAction();   		
	        		
	        		attributeContext.putAttribute("title", new Attribute(a.getTitle()));
	        		attributeContext.putAttribute("content", new Attribute(a.getContent()));
	        		attributeContext.putAttribute("head_extra", new Attribute(a.getHeadExtra()));
	        	}else if ( invocation.getAction() instanceof AjaxBaseAction )
	        	{
	        		AjaxBaseAction		a = (AjaxBaseAction)invocation.getAction();
	        		
	        		attributeContext.putAttribute("content", new Attribute(a.getContent()));      		
	        	}
        	}else if ( invocation.getResultCode().compareTo(ActionSupport.ERROR) == 0 )
        	{
        		Collection<String>  errs = ((ActionSupport)invocation.getAction()).getActionErrors();
        		String err = "";
        		
        		for (String str : errs) {
        			err += str + " - ";	        			
        		}
        		if ( err.endsWith(" - ") )
        			err = err.substring(0, err.length()-3);
        		
	        	if ( invocation.getAction() instanceof BaseAction )
	        	{
	        		BaseAction		a = (BaseAction)invocation.getAction();
	        		
	        		attributeContext.putAttribute("errTitle", new Attribute(a.getErrorTitle()));
	        		attributeContext.putAttribute("errStr", new Attribute(err));
	        	}else if ( invocation.getAction() instanceof AjaxBaseAction )
	        	{
	        		AjaxBaseAction		a = (AjaxBaseAction)invocation.getAction();
	        		
	        		attributeContext.putAttribute("errStr", new Attribute(err));
	        	}        		
        	}
        	
        } catch ( Exception ex )
        {
        	
        }
                
        container.render(location, request, response);
        container.endContext(request, response);     
        
        //container.render(location, request, response);
    }
}

